package com.xnet.common.utils;

import com.xnet.common.entity.TreeEntity;

import javax.swing.text.html.parser.Entity;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 树形结构通用类
 *
 * @author Xingyc
 * @date 2018-1-23 15:49:22
 */
public class TreeNodeUtils {

    /**
     * 将树形节点列表转换为树形结构
     *
     * @param treeList       所有tree列表
     * @param parentId       递归父节点
     * @param resultTreeList 结果列表
     * @return
     */
    public static List<TreeEntity> convertToTree(List<TreeEntity> treeList, String parentId, List<TreeEntity> resultTreeList) {

        List<TreeEntity> childList = treeList.stream().filter(x -> x.getParentId().equals(parentId)).collect(Collectors.toList());
        if (childList.size() > 0) {
            for (TreeEntity item : childList) {
                item.setParentNodes(parentId);
                item.setChildNodes(convertToTree(treeList, item.getId(), resultTreeList));
                if (parentId.equals("0")) {
                    resultTreeList.add(item);
                }
            }
        }
        return childList;
    }


    /**
     * 获取所有树节点向上追溯节点
     * @param wholeTreeList
     * @param filterTreeList
     * @param resultTreeList
     */
    public static void getWholeTreeChain(List<TreeEntity> wholeTreeList, List<TreeEntity> filterTreeList, List<TreeEntity> resultTreeList) {

        for (TreeEntity item : filterTreeList) {
            //去重处理
            if(!resultTreeList.stream().anyMatch(x->x.getId().equals(item.getId())))
            {
                resultTreeList.add(item);
            }
            if (!item.getParentId().equals("0")) {
                List<TreeEntity> tempTreeList = wholeTreeList.stream().filter(x -> x.getId().equals(item.getParentId())).collect(Collectors.toList());
                getWholeTreeChain(wholeTreeList, tempTreeList, resultTreeList);
            }
        }

    }

}
